package com.bykj.property.config.shiro.filter;

import com.alibaba.fastjson.JSONObject;

import com.bykj.property.controller.vo.response.ErrorCode;
import com.bykj.property.controller.vo.response.RespResult;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ShiroLoginFilter extends FormAuthenticationFilter {
private final Logger logger= LoggerFactory.getLogger(ShiroLoginFilter.class);
/**
* 在访问controller前判断是否登录，返回json，不进行重定向。
* @param request
* @param response
* @return true-继续往下执行，false-该filter过滤器已经处理，不继续执行其他过滤器
* @throws Exception
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if(isLoginRequest(request, response)) {
logger.info("this login url");
return true;
}
else {
logger.info("this is not login url");
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().write(JSONObject.toJSON(RespResult.error(ErrorCode.LOGIN_VAIL_FAIL)).toString());
return false;
}

/*
if (isAjax(request)) {

httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
RespResult result=new RespResult();
result.setCode(-1);
result.setData("login fail");
httpServletResponse.getWriter().write(JSONObject.toJSON(result).toString());
} else {
//saveRequestAndRedirectToLogin(request, response);
*//**
* @Mark 非ajax请求重定向为登录页面
*//*
httpServletResponse.sendRedirect("/login");
}
return false;*/
}

private boolean isAjax(ServletRequest request){
String header = ((HttpServletRequest) request).getHeader("X-Requested-With");

if("XMLHttpRequest".equalsIgnoreCase(header)){
return Boolean.TRUE;
}
return Boolean.FALSE;
}


}